package com.vnaloha.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * This class is create directory and save file
 * @author hieu
 *
 */
public class UploadUtil {
	
	/**
	 * The log
	 */
	private Logger logger = LoggerFactory.getLogger(UploadUtil.class);
	
	/**
	 * Upload file to directory
	 * @param request http request
	 * @param file multipartfile data
	 * @return true if success
	 */
	public boolean upload(HttpServletRequest request, MultipartFile file, String dir, String fileName) {
		
		logger.info("Trying save file to directory with request: " + request + " file: " + file);
		FileOutputStream fop = null;
		try {
			if (file.getSize() > 0) {
				// make dir
				File dirFile = new File(dir);
				if(!dirFile.exists()){
					dirFile.mkdirs();
				}
				
				// make file
				File fileUpload = new File(dir + fileName);
				
				fop = new FileOutputStream(fileUpload);
				if (!fileUpload.exists()) {
					fileUpload.createNewFile();
				}
				byte[] contentInBytes = file.getBytes();

				fop.write(contentInBytes);
				fop.flush();
				fop.close();
				
				return true;
			}
			
		} catch (Exception e) {
			logger.error("Error when save file to directory " + e, e);
		} finally {
			try {
				if (fop != null) {
					fop.close();
				}
			} catch (IOException e) {
				logger.debug(e.getMessage());
			}
		}
		return false;
	}
	
	/**
	 * Delete file in tomcat server
	 * @param request http request
	 * @param filePath this is file path of file like /public-resources/upload/2012/11/9/20121109101312708-m2.png
	 * it is a full path of file
	 * example http://domain.com/public-resources/upload/2012/11/9/20121109101312708-m2.png
	 * @return <code>true</code> if successfully
	 */
	public boolean delete(HttpServletRequest request, String filePath){
		// get directory in webapp
		String dir = getDir(request, filePath);
		// create file object
		File file = new File(dir);
		
		return file.delete();
	}
	
	/**
	 * Get current file in directory in webappp
	 * @param request htpp request
	 * @param filePath current file path
	 * @return a full path of file in directory
	 */
	private String getDir(HttpServletRequest request, String filePath) {
		String dir = request.getSession().getServletContext().getRealPath("/") + filePath;
		return dir;
	}

}
